package com.study.shengsiyuan.example09;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class _2_NioClient {


	public static void main(String[] args) throws IOException {
		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
		Selector selector = Selector.open();
		sc.register(selector, SelectionKey.OP_CONNECT);
		sc.connect(new InetSocketAddress("127.0.0.1", 8899));

		while(selector.select()>0) { // select() : 返回关注事件的数量,是阻塞方法
			Set<SelectionKey>  ssks =selector.selectedKeys();
			ByteBuffer bb= ByteBuffer.allocate(1024);
			for (SelectionKey selectionKey : ssks) {
				SocketChannel client = (SocketChannel)selectionKey.channel();
				if(selectionKey.isConnectable()) {
					bb.clear();
					if(client.isConnectionPending()) {
						client.finishConnect();
						// 读 --> 切换 --> 写
						bb.put( (LocalDateTime.now()+" -- 连接成功 ").getBytes() );
						bb.flip();
						client.write(bb);

						ExecutorService es = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
						es.execute(()->{
							while(true) {
								bb.clear();
								try {
									InputStreamReader input =new InputStreamReader(System.in);
									BufferedReader br =new BufferedReader(input);
									bb.put(br.readLine().getBytes());
									bb.flip();
									client.write(bb);
								}catch (Exception e) { }
							}

						});
					}
					client.register(selector, selectionKey.OP_READ);
				}else if(selectionKey.isReadable()) {
					bb.clear();
					int count = client.read(bb);
					if(count>0) {
						bb.flip();
						String rm= new String(bb.array(),0,count);
						System.out.println(rm);
					}
				}
				ssks.remove(selectionKey);
			}
		}
	}
}
